Java Method Parameter Passing: Pass by Value or Pass by Reference? A Comprehensive Guide

In Java, the essence of method parameter passing is **pass-by-value**, not pass-by-reference. Beginners often misunderstand it as "pass-by-reference" due to the behavior of objects with reference types, which is actually a confusion of concepts. Pass-by-value means the method receives a "copy" of the parameter; modifying the copy does not affect the original variable. Pass-by-reference, by contrast, transfers the "reference address," and modifications will affect the original object. In Java, all parameter passing is the former: - **Primitive types** (e.g., `int`): A copy of the value is passed. For example, in the `swap` method, modifying the copy does not affect the original variables (as demonstrated, the `swap` method cannot exchange `x` and `y`). - **Reference types** (e.g., objects, arrays): A copy of the reference address is passed. Although the copy and the original reference point to the same object, modifying the object's properties will affect the original object (e.g., changing the `name` attribute of a `Student` object). However, modifying the reference itself (to point to a new object) will not affect the original object (e.g., the `changeReference` method in the example does not alter the original object). Core conclusion: Java only has "pass-by-value." The special behavior of reference types arises from "shared access to the object via a copied reference address," not from the passing method being "pass-by-reference."

Read More